package com.wf.ew.JTServer.common.controller;

import com.wf.ew.JTServer.common.handle.JT809ServerInitialzer;
import com.wf.ew.JTServer.common.util.PropertiesUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.management.MalformedObjectNameException;

/**
 * @Author: Xiuming Lee
 * @Date: 2019/9/21 20:26
 * @Version 1.0
 * @Describe: 启动类
 */
@Component
public class JT809Server implements CommandLineRunner {

	private static Logger log = LoggerFactory.getLogger(JT809Server.class);

	private static int PORT;

	public static void aa(String[] args) throws MalformedObjectNameException {
	}

	private static void bind(final ServerBootstrap serverBootstrap, int port) {
		serverBootstrap.bind(port).addListener(future -> {
			if (future.isSuccess()) {
				log.info("JT809Server在端口：{}Start!", port);
				//CommonUtils.delDataTimer(); // 定时任务，定时删除垃圾数据
			} else {
				log.error("JT809Server在端口：{}Fail!", port);
			}
		});
	}

	@Override
	public void run(String... arg0) throws Exception {
		PORT = Integer.parseInt(PropertiesUtil.getProperty("port", "9099"));
		NioEventLoopGroup boosGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		final ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(boosGroup, workerGroup).channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true)
				.childOption(ChannelOption.TCP_NODELAY, true).childHandler(new JT809ServerInitialzer());
		bind(serverBootstrap, PORT);
	}
}
